package com.ftwj.demo.permission.controller;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ftwj.demo.config.swagger.DataType;
import com.ftwj.demo.config.swagger.ParamType;
import com.ftwj.demo.permission.entity.RoleBean;
import com.ftwj.demo.permission.service.RoleResourceService;
import com.ftwj.demo.permission.service.RoleService;
import com.ftwj.demo.global.shiro.ShiroUtil;
import com.ftwj.demo.utils.json.JsonUtil;
import com.ftwj.demo.utils.result.MessageEnum;
import com.ftwj.demo.utils.result.ResultBean;
import com.ftwj.demo.utils.validate.ValidateGroupKey;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
*
* <p>Title: RoleController</p>  
* <p>Description: 角色管理前端控制器</p>
* <p>Copyright: Copyright (c) 2020 </p>  
* <p>Company: 兰州飞天网景信息产业有限公司</p>    
* @author WangSLi
* @date 2020年4月4日 下午5:43:15
* @version V1.0
 */
@RestController
@RequestMapping("/role")
@Api(tags="角色管理接口", value="角色管理")
@Validated
public class RoleController {

	@Autowired
	private RoleService service;
	@Autowired
	private RoleResourceService roleResourceService;
	
	@GetMapping("page")
	@ApiOperation(value="分页列表条件查询（DONE）", notes="备注",code=0,httpMethod="GET")
    @ApiImplicitParams({
    		@ApiImplicitParam(name="page", value="当前页数", dataType=DataType.INTEGER, paramType=ParamType.QUERY, defaultValue="1")
    		,@ApiImplicitParam(name="limit", value="每页显示条数", dataType=DataType.INTEGER, paramType=ParamType.QUERY, defaultValue="10")
    })
	public ResultBean<?> page(@RequestParam(name="page",required = true) Integer page, @RequestParam(name="limit",required = true) Integer limit,
			@NotNull@RequestParam(name="name",required=false) String name) {
		IPage<RoleBean> ipage=new Page<RoleBean>(page, limit);
		RoleBean bean=new RoleBean();
		bean.setRoleName(name);
		IPage<Map<String, Object>> data = service.pageMaps(ipage, bean);
		return ResultBean.success(data);
	}
	
	@GetMapping("list")
	@ApiOperation(value="不分页列表条件查询（DONE）", notes="备注",code=0,httpMethod="GET")
	public ResultBean<?> list() {
		List<Map<String, Object>> data = service.listMaps();
		return ResultBean.success(data);
	}
	
	@GetMapping("info/{id}")
	@ApiOperation(value="角色详情（DONE）", notes="角色信息查询",code=0,httpMethod="GET")
    @ApiImplicitParams({
    		@ApiImplicitParam(name="id", value="角色编号", dataType=DataType.INTEGER, paramType=ParamType.PATH)
    })
	public ResultBean<?> info(@PathVariable Integer id) {
		RoleBean bean = service.getById(id);
		return ResultBean.success(bean);
	}
	
	@PostMapping("insert")
	@ApiOperation(value="角色保存（DONE）", notes="角色信息保存",code=0,httpMethod="POST")
	public ResultBean<?> insert(@RequestBody@Validated RoleBean bean) {
		bean.setCreateUser(ShiroUtil.getUserId());
		bean.setCreateTime(LocalDateTime.now());
		bean.setState(1);
		if(service.save(bean)) {
			return ResultBean.success();
		}else {
			return ResultBean.error(MessageEnum.SERVER_FAILED);
		}
	}
	
	@PutMapping("update")
	@ApiOperation(value="角色更新（DONE）", notes="角色信息保存",code=0,httpMethod="PUT")
	public ResultBean<?> update(@RequestBody@Validated(value=ValidateGroupKey.class) RoleBean bean) {
		if(service.updateById(bean)) {
			return ResultBean.success();
		}else {
			return ResultBean.error(MessageEnum.SERVER_FAILED);
		}
	}
	
	@DeleteMapping("delete/{id}")
	@ApiOperation(value="角色删除（DONE）", notes="角色信息删除",code=0,httpMethod="DELETE")
    @ApiImplicitParams({
    		@ApiImplicitParam(name="id", value="角色编号", dataType=DataType.INTEGER, paramType=ParamType.PATH)
    })
	public ResultBean<?> delete(@PathVariable@Positive(message="ID必须为不小于0的数字：{value}") Integer id) {
		if(service.removeById(id)) {
			return ResultBean.success();
		}else {
			return ResultBean.error(MessageEnum.SERVER_FAILED);
		}
	}
	
	/**
	 * <p>Title: saveRoleResource</p>  
	 * <p>Description: 保存角色资源</p>  
	 * @param roleId
	 * @param resourceId
	 * @return 
	 * @author HeYang
	 * @date 2020年4月23日  
	 * @version 1.0
	 */
	@PostMapping("/config/resource")
	@ApiOperation(value="保存角色资源", notes="备注",code=0,httpMethod="POST")
	public ResultBean<?> saveRoleResource(@RequestBody JSONObject json) {
		Integer[] resources = JsonUtil.toArray(json.getString("resources"), Integer.class);
		if(roleResourceService.saveRoleResource(json.getInteger("roleId"),resources)) {
			return ResultBean.success();
		}else {
			return ResultBean.error(250, "部分资源授权失败！");
		}
	}
	
}

